/**
 * 将数组结构化为树形结构
 */

let data = [
    {
        id: 1,
        pid: 0,
        title: 'aaa',
        path: '/a'
    },
    {
        id: 4,
        pid: 0,
        title: 'ddd',
        path: '/d'
    },
    {
        id: 2,
        pid: 1,
        title: 'bbb',
        path: '/a/b'
    },
    {
        id: 3,
        pid: 2,
        title: 'ccc',
        path: '/a/b/c'
    }
]

function dataFormat(arr) {
    let parents = arr.filter(p => p.pid === 0),
        children = arr.filter(c => c.pid !== 0)
    dataToTree(parents, children)

    function dataToTree(parents, children) {
        parents.map(p => {
            children.map((c, index) => {
                if (c.pid === p.id) {
                    let _children = JSON.parse(JSON.stringify(children))
                    _children.splice(index, 1)
                    dataToTree([c], _children)

                    if (p.children) {
                        p.children = c
                    } else {
                        p.children = [c]
                    }


                }
            })
        })
    }

    return parents
}

// let tree = dataFormat(data)
// console.log(tree)

//方式二：非递归  假的map结构
function dataFormat2(data) {
    let map = {},
        result = []
    data.forEach(item => map[item.id] = item)
    console.log('map', map)
    data.forEach(item => {
        // 获取当前节点的父节点
        let parent = map[item.pid]

        if (parent) {
            if (parent.children) {
                parent.children.push(item)
            } else {
                parent.children = [item]
            }
        } else {
            //父节点不存在 == pid=0
            result.push(item)
        }
    })
    return result

}

/*
map:
{
    '1': { id: 1, pid: 0, title: 'aaa', path: '/a' },
    '2': { id: 2, pid: 1, title: 'bbb', path: '/a/b' },
    '3': { id: 3, pid: 2, title: 'ccc', path: '/a/b/c' },
    '4': { id: 4, pid: 0, title: 'ddd', path: '/d' }

}
*/


let res2 = dataFormat2(data)
console.log(('res2', res2))

/*
[
  { id: 1, pid: 0, title: 'aaa', path: '/a', children: [ [Object] ] },
  { id: 4, pid: 0, title: 'ddd', path: '/d' }
]
  */